﻿using System;
using System.Collections.Generic;

namespace LinqExtensions
{
    public static class Search
    {
        public static int IndexOf<T>(this IEnumerable<T> source, T element, IEqualityComparer<T> equalityComparer)
        {
            if (source == null) throw new ArgumentNullException("source");
            if (equalityComparer == null) throw new ArgumentNullException("equalityComparer");

            return InternalIndexOf(source, element, equalityComparer);
        }

        internal static int InternalIndexOf<T>(IEnumerable<T> source, T element, IEqualityComparer<T> equalityComparer)
        {
            var indexedSource = source as IList<T>;
            if (indexedSource != null)
                return indexedSource.IndexOf(element, equalityComparer);

            var index = 0;
            foreach (var item in source)
            {
                if (equalityComparer.Equals(item, element))
                    return index;
                index++;
            }
            return -1;
        }
    }
}
